home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1995 November / EnigmA AMIGA RUN 02 (1995)(G.R. Edizioni)(IT)[!][issue 1995-11][Skylink CD].iso / earcd / util / arcer / gnutar10.lha / GnuTAR / GNUTarSource.LHA / source / tar.c < prev    next >
C/C++ Source or Header  |  1991-07-04  |  30KB  |  1,171 lines

  1. /* Tar -- a tape archiver.
  2.  
  3.     Copyright (C) 1988 Free Software Foundation
  4.  
  5. GNU tar is distributed in the hope that it will be useful, but WITHOUT ANY
  6. WARRANTY.  No author or distributor accepts responsibility to anyone
  7. for the consequences of using it or for whether it serves any
  8. particular purpose or works at all, unless he says so in writing.
  9. Refer to the GNU tar General Public License for full details.
  10.  
  11. Everyone is granted permission to copy, modify and redistribute GNU tar,
  12. but only under the conditions described in the GNU tar General Public
  13. License.  A copy of this license is supposed to have been given to you
  14. along with GNU tar so you can know your rights and responsibilities.  It
  15. should be in a file named COPYING.  Among other things, the copyright
  16. notice and this notice must be preserved on all copies.
  17.  
  18. In other words, go ahead and share GNU tar, but don't try to stop
  19. anyone else from sharing it farther.  Help stamp out software hoarding!
  20. */
  21.  
  22. /*
  23.  * A tar (tape archiver) program.
  24.  *
  25.  * Written by John Gilmore, ihnp4!hoptoad!gnu, starting 25 Aug 85.
  26.  *
  27.  * @(#)tar.c 1.34 11/6/87 - gnu
  28.  */
  29.  
  30. #include <stdio.h>
  31. #include <sys/types.h>        /* Needed for typedefs in tar.h */
  32. #include <sys/stat.h>        /* JF */
  33. #include "getopt.h"
  34.  
  35. #ifdef USG
  36. #define rindex strrchr
  37. #endif
  38.  
  39. #ifdef BSD42
  40. #include <sys/dir.h>
  41. #else
  42. #ifdef MSDOS
  43. #include <sys/dir.h>
  44. #else
  45. #ifdef USG
  46. #ifdef NDIR
  47. #include <ndir.h>
  48. #else
  49. #include <dirent.h>
  50. #endif
  51. #ifndef DIRECT
  52. #define direct dirent
  53. #endif
  54. #define DP_NAMELEN(x) strlen((x)->d_name)
  55. #else
  56. /*
  57.  * FIXME: On other systems there is no standard place for the header file
  58.  * for the portable directory access routines.    Change the #include line
  59.  * below to bring it in from wherever it is.
  60.  */
  61. #include "ndir.h"
  62. #endif
  63. #endif
  64. #endif
  65.  
  66. #ifndef DP_NAMELEN
  67. #define DP_NAMELEN(x)   (x)->d_namlen
  68. #endif
  69.  
  70. extern char    *malloc();
  71. extern char    *getenv();
  72. extern char    *strncpy();
  73. extern char    *index();
  74. extern char    *strcpy();      /* JF */
  75. extern char    *strcat();      /* JF */
  76.  
  77. extern char    *optarg;    /* Pointer to argument */
  78. extern int    optind;     /* Global argv index from getopt */
  79.  
  80. extern char    *ck_malloc();
  81. extern char    *ck_realloc();
  82. /*
  83.  * The following causes "tar.h" to produce definitions of all the
  84.  * global variables, rather than just "extern" declarations of them.
  85.  */
  86. #define TAR_EXTERN /**/
  87. #include "tar.h"
  88.  
  89. /*
  90.  * We should use a conversion routine that does reasonable error
  91.  * checking -- atoi doesn't.  For now, punt.  FIXME.
  92.  */
  93. #define intconv atoi
  94. extern int    getoldopt();
  95. extern void    read_and();
  96. extern void    list_archive();
  97. extern void    extract_archive();
  98. extern void    diff_archive();
  99. extern void    create_archive();
  100. extern void    update_archive();
  101. extern void    junk_archive();
  102.  
  103. /* JF */
  104. extern time_t    getdate();
  105.  
  106. time_t new_time;
  107.  
  108. static FILE    *namef;     /* File to read names from */
  109. static char    **n_argv;    /* Argv used by name routines */
  110. static int    n_argc;     /* Argc used by name routines */
  111. static char    **n_ind;    /* Store an array of names */
  112. static int    n_indalloc;    /* How big is the array? */
  113. static int    n_indused;    /* How many entries does it have? */
  114. static int    n_indscan;    /* How many of the entries have we scanned? */
  115.  
  116.  
  117. extern FILE *msg_file;
  118.  
  119. void    describe();
  120. void    options();
  121.  
  122. #ifndef S_IFLNK
  123. #define lstat stat
  124. #endif
  125.  
  126. #ifndef DEFBLOCKING
  127. #define DEFBLOCKING 20
  128. #endif
  129.  
  130. #ifndef DEF_AR_FILE
  131. #define DEF_AR_FILE "tar.out"
  132. #endif
  133.  
  134. /* For long options that unconditionally set a single flag, we have getopt
  135.    do it.  For the others, we share the code for the equivalent short
  136.    named option, the name of which is stored in the otherwise-unused `val'
  137.    field of the `struct option'; for long options that have no equivalent
  138.    short option, we use nongraphic characters as pseudo short option
  139.    characters, starting (for no particular reason) with character 10. */
  140.  
  141. struct option long_options[] =
  142. {
  143.     {"create",              0,      0,                      'c'},
  144.     {"append",              0,      0,                      'r'},
  145.     {"extract",             0,      0,                      'x'},
  146.     {"get",                 1,      0,                      'x'},
  147.     {"list",                0,      0,                      't'},
  148.     {"update",              0,      0,                      'u'},
  149.     {"catenate",            0,      0,                      'A'},
  150.     {"concatenate",         1,      0,                      'A'},
  151.     {"compare",             0,      0,                      'd'},
  152.     {"diff",                0,      0,                      'd'},
  153.     {"delete",              0,      0,                      14},
  154.     {"help",                0,      0,                      12},
  155.  
  156.     {"directory",           1,      0,                      'C'},
  157.     {"record-number",       0,      &f_sayblock,            1},
  158.     {"files-from",          1,      0,                      'T'},
  159.     {"volume",              1,      0,                      'V'},
  160.     {"exclude",             1,      0,                      'X'},
  161.     {"file",                1,      0,                      'f'},
  162.     {"block-size",          1,      0,                      'b'},
  163.     {"version",             0,      0,                      11},
  164.     {"verbose",             0,      &f_verbose,             1},
  165.  
  166.     {"read-full-blocks",    0,      &f_reblock,             1},
  167.     {"starting-file",       1,      0,                      'K'},
  168.     {"to-stdout",           0,      &f_exstdout,            1},
  169.     {"ignore-zeros",        0,      &f_ignorez,             1},
  170.     {"keep-old-files",      0,      0,                      'k'},
  171.     {"uncompress",          0,      &f_compress,            1},
  172.     {"same-permissions",    0,      &f_use_protection,      1},
  173.     {"preserve-permissions",0,      &f_use_protection,      1},
  174.     {"modification-time",   0,      &f_modified,            1},
  175.     {"preserve",            0,      0,                      10},
  176.     {"same-order",          0,      &f_sorted_names,        1},
  177.     {"same-owner",          0,      &f_do_chown,            1},
  178.     {"preserve-order",      0,      &f_sorted_names,        1},
  179.  
  180.     {"newer",               0,      0,                      'N'},
  181.     {"after-date",          1,      0,                      'N'},
  182.     {"newer-mtime",         1,      0,                      13},
  183.     {"incremental",         0,      0,                      'G'},
  184.     {"listed-imcremental",  1,      0,                      'g'},
  185.     {"multi-volume",        0,      &f_multivol,            1},
  186.     {"info-script",         1,      &f_run_script_at_end,   1},
  187.     {"absolute-paths",      0,      &f_absolute_paths,      1},
  188.     {"interactive",         0,      &f_confirm,             1},
  189.  
  190.     {"verify",              0,      &f_verify,              1},
  191.     {"dereference",         0,      &f_follow_links,        1},
  192.     {"one-file-system",     0,      &f_local_filesys,       1},
  193.     {"old-archive",         0,      0,                      'o'},
  194.     {"portability",         0,      0,                      'o'},
  195.     {"compress",            0,      &f_compress,            1},
  196.     {"compress-block",      0,      &f_compress,            2},
  197.     {"sparse",              0,      &f_sparse_files,        1},
  198.  
  199.     {0, 0, 0, 0}
  200. };
  201.  
  202. /*
  203.  * Main routine for tar.
  204.  */
  205. main(argc, argv)
  206.     int    argc;
  207.     char    **argv;
  208. {
  209.     tar = argv[0];        /* JF: was "tar" Set program name */
  210.  
  211.     options(argc, argv);
  212.  
  213.     if(!n_argv)
  214.         name_init(argc, argv);
  215.  
  216.     switch(cmd_mode) {
  217.     case CMD_CAT:
  218.     case CMD_UPDATE:
  219.     case CMD_APPEND:
  220.         update_archive();
  221.         break;
  222.     case CMD_DELETE:
  223.         junk_archive();
  224.         break;
  225.     case CMD_CREATE:
  226.         create_archive();
  227.         break;
  228.     case CMD_EXTRACT:
  229.         extr_init();
  230.         read_and(extract_archive);
  231.         break;
  232.     case CMD_LIST:
  233.         read_and(list_archive);
  234.         break;
  235.     case CMD_DIFF:
  236.         diff_init();
  237.         read_and(diff_archive);
  238.         break;
  239.     case CMD_NONE:
  240.         msg("you must specify exactly one of the r, c, t, x, or d options\n");
  241.         fprintf(stderr,"For more information, type ``%s +help''.\n",tar);
  242.         exit(EX_ARGSBAD);
  243.     }
  244.     exit(0);
  245.     /* NOTREACHED */
  246. }
  247.  
  248.  
  249. /*
  250.  * Parse the options for tar.
  251.  */
  252. void
  253. options(argc, argv)
  254.     int    argc;
  255.     char    **argv;
  256. {
  257.     register int    c;        /* Option letter */
  258.     int        ind = -1;
  259.     extern char version_string[];
  260.  
  261.     /* Set default option values */
  262.     blocking = DEFBLOCKING;     /* From Makefile */
  263.     ar_file = getenv("TAPE");       /* From environment, or */
  264.     if (ar_file == 0)
  265.         ar_file = DEF_AR_FILE;    /* From Makefile */
  266.  
  267.     /* Parse options */
  268.     while ((c = getoldopt(argc, argv,
  269.                   "-01234567Ab:BcC:df:F:g:GhikK:lmMN:oOpPrRsStT:uvV:wWxX:zZ",
  270.                   long_options, &ind)) != EOF) {
  271.         switch (c) {
  272.         case 0:     /* long options that set a single flag */
  273.             break;
  274.         case 1:
  275.             /* File name or non-parsed option */
  276.             name_add(optarg);
  277.             break;
  278.         case 'C':
  279.             name_add("-C");
  280.             name_add(optarg);
  281.             break;
  282.         case 10:    /* preserve */
  283.             f_use_protection = f_sorted_names = 1;
  284.             break;
  285.         case 11:    /* version */
  286.             fprintf(stderr,"%s\n",version_string);
  287.             break;
  288.         case 12:    /* help */
  289.             fprintf(stderr,"This is GNU tar, the tape archiving program.\n");
  290.             describe();
  291.             exit(1);
  292.         case 13:
  293.             f_new_files++;
  294.             goto get_newer;
  295.  
  296.         case 14:            /* Delete in the archive */
  297.             if(cmd_mode!=CMD_NONE)
  298.                 goto badopt;
  299.             cmd_mode=CMD_DELETE;
  300.             break;
  301.  
  302.         case 'g':                       /* We are making a GNU dump; save
  303.                            directories at the beginning of
  304.                            the archive, and include in each
  305.                            directory its contents */
  306.             if(f_oldarch)
  307.                 goto badopt;
  308.             f_gnudump++;
  309.             gnu_dumpfile=optarg;
  310.             break;
  311.  
  312.  
  313.         case '0':
  314.         case '1':
  315.         case '2':
  316.         case '3':
  317.         case '4':
  318.         case '5':
  319.         case '6':
  320.         case '7':
  321.             {
  322.                 /* JF this'll have to be modified for other
  323.                    systems, of course! */
  324.                 int d,add;
  325.                 static char buf[50];
  326.  
  327.                 d=getoldopt(argc,argv,"lmh");
  328. #ifdef MAYBEDEF
  329.                 sprintf(buf,"/dev/rmt/%d%c",c,d);
  330. #else
  331. #ifndef LOW_NUM
  332. #define LOW_NUM 0
  333. #define MID_NUM 8
  334. #define HGH_NUM 16
  335. #endif
  336.                 if(d=='l') add=LOW_NUM;
  337.                 else if(d=='m') add=MID_NUM;
  338.                 else if(d=='h') add=HGH_NUM;
  339.                 else goto badopt;
  340.  
  341.                 sprintf(buf,"/dev/rmt%d",add+c-'0');
  342. #endif
  343.                 ar_file=buf;
  344.             }
  345.             break;
  346.  
  347.         case 'A':                       /* Arguments are tar files,
  348.                            just cat them onto the end
  349.                            of the archive.  */
  350.             if(cmd_mode!=CMD_NONE)
  351.                 goto badopt;
  352.             cmd_mode=CMD_CAT;
  353.             break;
  354.  
  355.         case 'b':                       /* Set blocking factor */
  356.             blocking = intconv(optarg);
  357.             break;
  358.  
  359.         case 'B':                       /* Try to reblock input */
  360.             f_reblock++;        /* For reading 4.2BSD pipes */
  361.             break;
  362.  
  363.         case 'c':                       /* Create an archive */
  364.             if(cmd_mode!=CMD_NONE)
  365.                 goto badopt;
  366.             cmd_mode=CMD_CREATE;
  367.             break;
  368.  
  369. /*        case 'C':
  370.             if(chdir(optarg)<0)
  371.                 msg_perror("Can't change directory to %d",optarg);
  372.             break; */
  373.  
  374.         case 'd':                       /* Find difference tape/disk */
  375.             if(cmd_mode!=CMD_NONE)
  376.                 goto badopt;
  377.             cmd_mode=CMD_DIFF;
  378.             break;
  379.  
  380.         case 'f':                       /* Use ar_file for the archive */
  381.             ar_file = optarg;
  382.             break;
  383.  
  384.         case 'F':
  385.             /* Since -F is only useful with -M , make it implied */
  386.             f_run_script_at_end++;    /* run this script at the end */
  387.             info_script = optarg;    /* of each tape */
  388.             f_multivol++;
  389.             break;
  390.  
  391.         case 'G':                       /* We are making a GNU dump; save
  392.                            directories at the beginning of
  393.                            the archive, and include in each
  394.                            directory its contents */
  395.             if(f_oldarch)
  396.                 goto badopt;
  397.             f_gnudump++;
  398.             gnu_dumpfile=0;
  399.             break;
  400.  
  401.         case 'h':
  402.             f_follow_links++;    /* follow symbolic links */
  403.             break;
  404.  
  405.         case 'i':
  406.             f_ignorez++;        /* Ignore zero records (eofs) */
  407.             /*
  408.              * This can't be the default, because Unix tar
  409.              * writes two records of zeros, then pads out the
  410.              * block with garbage.
  411.              */
  412.             break;
  413.  
  414.         case 'k':                       /* Don't overwrite files */
  415. #ifdef NO_OPEN3
  416.             msg("can't do -k option on this system");
  417.             exit(EX_ARGSBAD);
  418. #else
  419.             f_keep++;
  420. #endif
  421.             break;
  422.  
  423.         case 'K':
  424.             f_startfile++;
  425.             addname(optarg);
  426.             break;
  427.  
  428.         case 'l':                       /* When dumping directories, don't
  429.                            dump files/subdirectories that are
  430.                            on other filesystems. */
  431.             f_local_filesys++;
  432.             break;
  433.  
  434.         case 'm':
  435.             f_modified++;
  436.             break;
  437.  
  438.         case 'M':                       /* Make Multivolume archive:
  439.                            When we can't write any more
  440.                            into the archive, re-open it,
  441.                            and continue writing */
  442.             f_multivol++;
  443.             break;
  444.  
  445.         case 'N':                       /* Only write files newer than X */
  446.         get_newer:
  447.             f_new_files++;
  448.             new_time=getdate(optarg,(struct timeb *)0);
  449.             break;
  450.  
  451.         case 'o':                       /* Generate old archive */
  452.             if(f_gnudump /* || f_dironly */)
  453.                 goto badopt;
  454.             f_oldarch++;
  455.             break;
  456.  
  457.         case 'O':
  458.             f_exstdout++;
  459.             break;
  460.  
  461.         case 'p':
  462.             f_use_protection++;
  463.             break;
  464.  
  465.         case 'P':
  466.             f_absolute_paths++;
  467.             break;
  468.  
  469.         case 'r':                       /* Append files to the archive */
  470.             if(cmd_mode!=CMD_NONE)
  471.                 goto badopt;
  472.             cmd_mode=CMD_APPEND;
  473.             break;
  474.  
  475.         case 'R':
  476.             f_sayblock++;        /* Print block #s for debug */
  477.             break;            /* of bad tar archives */
  478.  
  479.         case 's':
  480.             f_sorted_names++;    /* Names to extr are sorted */
  481.             break;
  482.  
  483.         case 'S':                       /* deal with sparse files */
  484.             f_sparse_files++;
  485.             break;
  486.         case 't':
  487.             if(cmd_mode!=CMD_NONE)
  488.                 goto badopt;
  489.             cmd_mode=CMD_LIST;
  490.             f_verbose++;        /* "t" output == "cv" or "xv" */
  491.             break;
  492.  
  493.         case 'T':
  494.             name_file = optarg;
  495.             f_namefile++;
  496.             break;
  497.  
  498.         case 'u':                       /* Append files to the archive that
  499.                            aren't there, or are newer than the
  500.                            copy in the archive */
  501.             if(cmd_mode!=CMD_NONE)
  502.                 goto badopt;
  503.             cmd_mode=CMD_UPDATE;
  504.             break;
  505.  
  506.         case 'v':
  507.             f_verbose++;
  508.             break;
  509.  
  510.         case 'V':
  511.             f_volhdr=optarg;
  512.             break;
  513.  
  514.         case 'w':
  515.             f_confirm++;
  516.             break;
  517.  
  518.         case 'W':
  519.             f_verify++;
  520.             break;
  521.  
  522.         case 'x':                       /* Extract files from the archive */
  523.             if(cmd_mode!=CMD_NONE)
  524.                 goto badopt;
  525.             cmd_mode=CMD_EXTRACT;
  526.             break;
  527.  
  528.         case 'X':
  529.             f_exclude++;
  530.             add_exclude(optarg);
  531.             break;
  532.  
  533.         case 'z':               /* Easy to type */
  534.         case 'Z':               /* Like the filename extension .Z */
  535.             f_compress++;
  536.             break;
  537.  
  538.         case '?':
  539.         badopt:
  540.             msg("Unknown option.  Use '%s +help' for a complete list of options.", tar);
  541.             exit(EX_ARGSBAD);
  542.  
  543.         }
  544.     }
  545.  
  546.     blocksize = blocking * RECORDSIZE;
  547. }
  548.  
  549.  
  550. /*
  551.  * Print as much help as the user's gonna get.
  552.  *
  553.  * We have to sprinkle in the KLUDGE lines because too many compilers
  554.  * cannot handle character strings longer than about 512 bytes.  Yuk!
  555.  * In particular, MSDOS and Xenix MSC and PDP-11 V7 Unix have this
  556.  * problem.
  557.  */
  558. void
  559. describe()
  560. {
  561.     msg("choose one of the following:");
  562.     fputs("\
  563. -A, +catenate        append tar files to an archive\n\
  564. -c, +create        create a new archive\n\
  565. -d, +diff        find differences between archive and file system\n\
  566.     +delete        delete from the archive (not for use on mag tapes!)\n\
  567. -r, +append        append files to the end of an archive\n\
  568. -t, +list        list the contents of an archive\n\
  569. -u, +update        only append files that are newer than copy in archive\n\
  570. -x, +extract        extract files from an archive\n",stderr);
  571.  
  572.     fputs("\
  573. Other options:\n\
  574. -b, +block-size N    block size of Nx512 bytes\n\
  575. -B, +read-full-blocks    reblock as we read (for reading 4.2BSD pipes)\n\
  576. -C, +directory dir    change to directory DIR\n\
  577. ", stderr); /* KLUDGE */ fputs("\
  578. -f, +file F        use archive file or device F (or hostname:/dev/file)\n\
  579. -G, +incremental F    create/list/extract GNU-format incremental backup\n\
  580. -h, +dereference    don't dump symlinks; dump the files they point to\n\
  581. -i, +ignore-zeros    ignore blocks of zeros in archive (normally mean EOF)\n\
  582. -k, +keep-old-files    keep existing files; don't overwrite them from archive\n\
  583. -K, +starting-file file begin at FILE in the archive\n\
  584. -l, +one-file-system    stay in local file system when creating an archive\n\
  585. ", stderr); /* KLUDGE */ fputs("\
  586. -m, +modification-time    don't extract file modified time\n\
  587. -M, +multi-volume    create/list/extract multi-volume archive\n\
  588. -N, +after-date date    only store files newer than DATE\n\
  589. -o, +old-archive    write a V7 format archive, rather than ANSI format\n\
  590. -O, +to-stdout        extract files to standard output\n\
  591. -p, +same-permissions    extract all protection information\n\
  592. -P, +absolute-paths    don't strip leading `/'s from file names\n\
  593. +preserve        like -p -s\n\
  594. -R, +record-number    show record number within archive with each message\n\
  595. -s, +same-order     list of names to extract is sorted to match archive\n\
  596. -S, +sparse        handle sparse files efficiently\n\
  597. ", stderr); /* KLUDGE */ fputs("\
  598. -T, +files-from F    get names to extract or create from file F\n\
  599. -v, +verbose        verbosely list files processed\n\
  600. -V, +volume VNAM    create archive with volume name VNAM\n\
  601. +version        print tar program version number\n\
  602. -w, +interactive    ask for confirmation for every action\n\
  603. -W, +verify        attempt to verify the archive after writing it\n\
  604. -X, +exclude FILE    exclude files listed in FILE\n\
  605. -z, -Z, +compress    filter the archive through compress\n\
  606. -[0-7][lmh]        specify drive and density\n\
  607. ", stderr);
  608. }
  609.  
  610. name_add(name)
  611. char *name;
  612. {
  613.     if(n_indalloc==n_indused) {
  614.         n_indalloc+=10;
  615.         n_ind=(char **)(n_indused ? ck_realloc(n_ind,n_indalloc*sizeof(int)) : ck_malloc(n_indalloc*sizeof(int)));
  616.     }
  617.     n_ind[n_indused++]=name;
  618. }
  619.  
  620. /*
  621.  * Set up to gather file names for tar.
  622.  *
  623.  * They can either come from stdin or from argv.
  624.  */
  625. name_init(argc, argv)
  626.     int    argc;
  627.     char    **argv;
  628. {
  629.  
  630.     if (f_namefile) {
  631.         if (optind < argc) {
  632.             msg("too many args with -T option");
  633.             exit(EX_ARGSBAD);
  634.         }
  635.         if (!strcmp(name_file, "-")) {
  636.             namef = stdin;
  637.         } else {
  638.             namef = fopen(name_file, "r");
  639.             if (namef == NULL) {
  640.                 msg_perror("can't open file %s",name_file);
  641.                 exit(EX_BADFILE);
  642.             }
  643.         }
  644.     } else {
  645.         /* Get file names from argv, after options. */
  646.         n_argc = argc;
  647.         n_argv = argv;
  648.     }
  649. }
  650.  
  651. /*
  652.  * Get the next name from argv or the name file.
  653.  *
  654.  * Result is in static storage and can't be relied upon across two calls.
  655.  */
  656.  
  657. /* C is non-zero if we should deal with -C */
  658. char *
  659. name_next(c)
  660. {
  661.     static char    buffer[NAMSIZ+2];    /* Holding pattern */
  662.     register char    *p;
  663.     register char    *q = 0;
  664.     extern char *un_quote_string();
  665.  
  666.  tryagain:
  667.     if (namef == NULL) {
  668.         if(n_indscan<n_indused)
  669.             p=n_ind[n_indscan++];
  670.         else if (optind < n_argc)
  671.             /* Names come from argv, after options */
  672.             p=n_argv[optind++];
  673.         else {
  674.             if(q)
  675.                 msg("Missing filename after -C");
  676.             return NULL;
  677.         }
  678.  
  679.         /* JF trivial support for -C option.  I don't know if
  680.            chdir'ing at this point is dangerous or not.
  681.            It seems to work, which is all I ask. */
  682.         if(c && !q && p[0]=='-' && p[1]=='C' && p[2]=='\0') {
  683.             q=p;
  684.             goto tryagain;
  685.         }
  686.         if(q) {
  687.             if(chdir(p)<0)
  688.                 msg_perror("Can't chdir to %s",p);
  689.             q=0;
  690.             goto tryagain;
  691.         }
  692.         /* End of JF quick -C hack */
  693.  
  694.         if(f_exclude && check_exclude(p))
  695.             goto tryagain;
  696.         return un_quote_string(p);
  697.     }
  698.     while(p = fgets(buffer, NAMSIZ+1 /*nl*/, namef)) {
  699.         q = p+strlen(p)-1;              /* Find the newline */
  700.         if (q <= p)                     /* Ignore empty lines */
  701.             continue;
  702.         *q-- = '\0';                    /* Zap the newline */
  703.         while (q > p && *q == '/')      /* Zap trailing /s */
  704.             *q-- = '\0';
  705.         if(f_exclude && check_exclude(p))
  706.             goto tryagain;
  707.         return un_quote_string(p);
  708.     }
  709.     return NULL;
  710. }
  711.  
  712.  
  713. /*
  714.  * Close the name file, if any.
  715.  */
  716. name_close()
  717. {
  718.  
  719.     if (namef != NULL && namef != stdin) fclose(namef);
  720. }
  721.  
  722.  
  723. /*
  724.  * Gather names in a list for scanning.
  725.  * Could hash them later if we really care.
  726.  *
  727.  * If the names are already sorted to match the archive, we just
  728.  * read them one by one.  name_gather reads the first one, and it
  729.  * is called by name_match as appropriate to read the next ones.
  730.  * At EOF, the last name read is just left in the buffer.
  731.  * This option lets users of small machines extract an arbitrary
  732.  * number of files by doing "tar t" and editing down the list of files.
  733.  */
  734. name_gather()
  735. {
  736.     register char *p;
  737.     static struct name namebuf[1];    /* One-name buffer */
  738.     static char *chdir_name;
  739.  
  740.     if (f_sorted_names) {
  741.         p = name_next(0);
  742.         if (p) {
  743.             if(*p=='-' && p[1]=='C' && p[2]=='\0') {
  744.                 chdir_name=name_next(0);
  745.                 p=name_next(0);
  746.                 if(!p) {
  747.                     msg("Missing file name after -C");
  748.                     exit(EX_ARGSBAD);
  749.                 }
  750.                 namebuf[0].change_dir=chdir_name;
  751.             }
  752.             namebuf[0].length = strlen(p);
  753.             if (namebuf[0].length >= sizeof namebuf[0].name) {
  754.                 msg("Argument name '%s' too long.",p);
  755.                 namebuf[0].length = (sizeof namebuf[0].name) - 1;
  756.             }
  757.             strncpy(namebuf[0].name, p, namebuf[0].length);
  758.             namebuf[0].name[ namebuf[0].length ] = 0;
  759.             namebuf[0].next = (struct name *)NULL;
  760.             namebuf[0].found = 0;
  761.             namelist = namebuf;
  762.             namelast = namelist;
  763.         }
  764.         return;
  765.     }
  766.  
  767.     /* Non sorted names -- read them all in */
  768.     while (p = name_next(0))
  769.         addname(p);
  770. }
  771.  
  772. /*
  773.  * Add a name to the namelist.
  774.  */
  775. addname(name)
  776.     char    *name;            /* pointer to name */
  777. {
  778.     register int    i;        /* Length of string */
  779.     register struct name    *p;    /* Current struct pointer */
  780.     static char *chdir_name;
  781.     char *new_name();
  782. #define MAXPATHLEN 1024
  783.  
  784.     if(name[0]=='-' && name[1]=='C' && name[2]=='\0') {
  785.         chdir_name=name_next(0);
  786.         name=name_next(0);
  787.         if(!name) {
  788.             msg("Missing file name after -C");
  789.             exit(EX_ARGSBAD);
  790.         }
  791.         if(chdir_name[0]!='/') {
  792.             static char path[MAXPATHLEN];
  793. #if defined(MSDOS) || defined(USG)
  794.             int getcwd();
  795.  
  796.             if(!getcwd(path,MAXPATHLEN))
  797.                 msg("Couldn't get current directory.");
  798.                 exit(EX_SYSTEM);
  799. #else
  800.             char *getwd();
  801.  
  802.             if(!getwd(path)) {
  803.                 msg("Couldn't get current directory: %s",path);
  804.                 exit(EX_SYSTEM);
  805.             }
  806. #endif
  807.             chdir_name=new_name(path,chdir_name);
  808.         }
  809.     }
  810.  
  811.     i = strlen(name);
  812.     /*NOSTRICT*/
  813.     p = (struct name *)
  814.         malloc((unsigned)(i + sizeof(struct name) - NAMSIZ));
  815.     if (!p) {
  816.         msg("cannot allocate mem for name '%s'.",name);
  817.         exit(EX_SYSTEM);
  818.     }
  819.     p->next = (struct name *)NULL;
  820.     p->length = i;
  821.     strncpy(p->name, name, i);
  822.     p->name[i] = '\0';      /* Null term */
  823.     p->found = 0;
  824.     p->regexp = 0;        /* Assume not a regular expression */
  825.     p->firstch = 1;     /* Assume first char is literal */
  826.     p->change_dir=chdir_name;
  827.     p->dir_contents = 0;    /* JF */
  828.     if (index(name, '*') || index(name, '[') || index(name, '?')) {
  829.         p->regexp = 1;    /* No, it's a regexp */
  830.         if (name[0] == '*' || name[0] == '[' || name[0] == '?')
  831.             p->firstch = 0;     /* Not even 1st char literal */
  832.     }
  833.  
  834.     if (namelast) namelast->next = p;
  835.     namelast = p;
  836.     if (!namelist) namelist = p;
  837. }
  838. /*
  839.  * Match a name from an archive, p, with a name from the namelist.
  840.  */
  841. name_match(p)
  842.     register char *p;
  843. {
  844.     register struct name    *nlp;
  845.     register int        len;
  846.  
  847. again:
  848.     if (0 == (nlp = namelist))      /* Empty namelist is easy */
  849.         return 1;
  850.     len = strlen(p);
  851.     for (; nlp != 0; nlp = nlp->next) {
  852.         /* If first chars don't match, quick skip */
  853.         if (nlp->firstch && nlp->name[0] != p[0])
  854.             continue;
  855.  
  856.         /* Regular expressions */
  857.         if (nlp->regexp) {
  858.             if (wildmat(p, nlp->name)) {
  859.                 nlp->found = 1; /* Remember it matched */
  860.                 if(f_startfile) {
  861.                     free((void *)namelist);
  862.                     namelist=0;
  863.                 }
  864.                 if(nlp->change_dir && chdir(nlp->change_dir))
  865.                     msg_perror("Can't change to directory %s",nlp->change_dir);
  866.                 return 1;    /* We got a match */
  867.             }
  868.             continue;
  869.         }
  870.  
  871.         /* Plain Old Strings */
  872.         if (nlp->length <= len          /* Archive len >= specified */
  873.          && (p[nlp->length] == '\0' || p[nlp->length] == '/')
  874.                         /* Full match on file/dirname */
  875.          && strncmp(p, nlp->name, nlp->length) == 0) /* Name compare */
  876.         {
  877.             nlp->found = 1;     /* Remember it matched */
  878.             if(f_startfile) {
  879.                 free((void *)namelist);
  880.                 namelist = 0;
  881.             }
  882.             if(nlp->change_dir && chdir(nlp->change_dir))
  883.                 msg_perror("Can't change to directory %s",nlp->change_dir);
  884.             return 1;        /* We got a match */
  885.         }
  886.     }
  887.  
  888.     /*
  889.      * Filename from archive not found in namelist.
  890.      * If we have the whole namelist here, just return 0.
  891.      * Otherwise, read the next name in and compare it.
  892.      * If this was the last name, namelist->found will remain on.
  893.      * If not, we loop to compare the newly read name.
  894.      */
  895.     if (f_sorted_names && namelist->found) {
  896.         name_gather();          /* Read one more */
  897.         if (!namelist->found) goto again;
  898.     }
  899.     return 0;
  900. }
  901.  
  902.  
  903. /*
  904.  * Print the names of things in the namelist that were not matched.
  905.  */
  906. names_notfound()
  907. {
  908.     register struct name    *nlp;
  909.     register char        *p;
  910.  
  911.     for (nlp = namelist; nlp != 0; nlp = nlp->next) {
  912.         if (!nlp->found)
  913.             msg("%s not found in archive",nlp->name);
  914.  
  915.         /*
  916.          * We could free() the list, but the process is about
  917.          * to die anyway, so save some CPU time.  Amigas and
  918.          * other similarly broken software will need to waste
  919.          * the time, though.
  920.          */
  921. #ifndef unix
  922.         if (!f_sorted_names)
  923.             free(nlp);
  924. #endif
  925.     }
  926.     namelist = (struct name *)NULL;
  927.     namelast = (struct name *)NULL;
  928.  
  929.     if (f_sorted_names) {
  930.         while (0 != (p = name_next(1)))
  931.             msg("%s not found in archive", p);
  932.     }
  933. }
  934.  
  935. /* These next routines were created by JF */
  936.  
  937. name_expand()
  938. {
  939. ;
  940. }
  941.  
  942. /* This is like name_match(), except that it returns a pointer to the name
  943.    it matched, and doesn't set ->found  The caller will have to do that
  944.    if it wants to.  Oh, and if the namelist is empty, it returns 0, unlike
  945.    name_match(), which returns TRUE */
  946.  
  947. struct name *
  948. name_scan(p)
  949. register char *p;
  950. {
  951.     register struct name    *nlp;
  952.     register int        len;
  953.  
  954. again:
  955.     if (0 == (nlp = namelist))      /* Empty namelist is easy */
  956.         return 0;
  957.     len = strlen(p);
  958.     for (; nlp != 0; nlp = nlp->next) {
  959.         /* If first chars don't match, quick skip */
  960.         if (nlp->firstch && nlp->name[0] != p[0])
  961.             continue;
  962.  
  963.         /* Regular expressions */
  964.         if (nlp->regexp) {
  965.             if (wildmat(p, nlp->name))
  966.                 return nlp;    /* We got a match */
  967.             continue;
  968.         }
  969.  
  970.         /* Plain Old Strings */
  971.         if (nlp->length <= len          /* Archive len >= specified */
  972.          && (p[nlp->length] == '\0' || p[nlp->length] == '/')
  973.                         /* Full match on file/dirname */
  974.          && strncmp(p, nlp->name, nlp->length) == 0) /* Name compare */
  975.             return nlp;        /* We got a match */
  976.     }
  977.  
  978.     /*
  979.      * Filename from archive not found in namelist.
  980.      * If we have the whole namelist here, just return 0.
  981.      * Otherwise, read the next name in and compare it.
  982.      * If this was the last name, namelist->found will remain on.
  983.      * If not, we loop to compare the newly read name.
  984.      */
  985.     if (f_sorted_names && namelist->found) {
  986.         name_gather();          /* Read one more */
  987.         if (!namelist->found) goto again;
  988.     }
  989.     return (struct name *) 0;
  990. }
  991.  
  992. /* This returns a name from the namelist which doesn't have ->found set.
  993.    It sets ->found before returning, so successive calls will find and return
  994.    all the non-found names in the namelist */
  995.  
  996. struct name *gnu_list_name;
  997.  
  998. char *
  999. name_from_list()
  1000. {
  1001.     if(!gnu_list_name)
  1002.         gnu_list_name = namelist;
  1003.     while(gnu_list_name && gnu_list_name->found)
  1004.         gnu_list_name=gnu_list_name->next;
  1005.     if(gnu_list_name) {
  1006.         gnu_list_name->found++;
  1007.         if(gnu_list_name->change_dir)
  1008.             if(chdir(gnu_list_name->change_dir)<0)
  1009.                 msg_perror("can't chdir to %s",gnu_list_name->change_dir);
  1010.         return gnu_list_name->name;
  1011.     }
  1012.     return (char *)0;
  1013. }
  1014.  
  1015. blank_name_list()
  1016. {
  1017.     struct name *n;
  1018.  
  1019.     gnu_list_name = 0;
  1020.     for(n=namelist;n;n=n->next)
  1021.         n->found = 0;
  1022. }
  1023.  
  1024. char *
  1025. new_name(path,name)
  1026. char *path,*name;
  1027. {
  1028.     char *path_buf;
  1029.  
  1030.     path_buf=(char *)malloc(strlen(path)+strlen(name)+2);
  1031.     if(path_buf==0) {
  1032.         msg("Can't allocate memory for name '%s/%s",path,name);
  1033.         exit(EX_SYSTEM);
  1034.     }
  1035.     (void) sprintf(path_buf,"%s/%s",path,name);
  1036.     return path_buf;
  1037. }
  1038.  
  1039. /* returns non-zero if the luser typed 'y' or 'Y', zero otherwise. */
  1040.  
  1041. int
  1042. confirm(action,file)
  1043. char *action, *file;
  1044. {
  1045.     int    c,nl;
  1046.     static FILE *confirm_file = 0;
  1047.     extern FILE *msg_file;
  1048.     extern char TTY_NAME[];
  1049.  
  1050.     fprintf(msg_file,"%s %s?", action, file);
  1051.     fflush(msg_file);
  1052.     if(!confirm_file) {
  1053.         confirm_file = (archive == 0) ? fopen(TTY_NAME, "r") : stdin;
  1054.         if(!confirm_file) {
  1055.             msg("Can't read confirmation from user");
  1056.             exit(EX_SYSTEM);
  1057.         }
  1058.     }
  1059.     c=getc(confirm_file);
  1060.     for(nl = c; nl != '\n' && nl != EOF; nl = getc(confirm_file))
  1061.         ;
  1062.     return (c=='y' || c=='Y');
  1063. }
  1064.  
  1065. char *x_buffer = 0;
  1066. int size_x_buffer;
  1067. int free_x_buffer;
  1068.  
  1069. char **exclude = 0;
  1070. int size_exclude = 0;
  1071. int free_exclude = 0;
  1072.  
  1073. char **re_exclude = 0;
  1074. int size_re_exclude = 0;
  1075. int free_re_exclude = 0;
  1076.  
  1077. add_exclude(file)
  1078. char *file;
  1079. {
  1080.     FILE *fp;
  1081.     static char buf[1024];
  1082.     extern char *rindex();
  1083.  
  1084.     if(strcmp(file, "-"))
  1085.         fp=fopen(file,"r");
  1086.     else
  1087.         /* Let's hope the person knows what they're doing. */
  1088.         /* Using -X - -T - -f - will get you *REALLY* strange
  1089.            results. . . */
  1090.         fp=stdin;
  1091.  
  1092.     if(!fp) {
  1093.         msg_perror("can't open %s",file);
  1094.         exit(2);
  1095.     }
  1096.     while(fgets(buf,1024,fp)) {
  1097.         int size_buf;
  1098.         char *end_str;
  1099.  
  1100.         end_str=rindex(buf,'\n');
  1101.         if(end_str)
  1102.             *end_str='\0';
  1103.  
  1104.         un_quote_string(buf);
  1105.         size_buf = strlen(buf);
  1106.  
  1107.         if(x_buffer==0) {
  1108.             x_buffer = (char *)ck_malloc(size_buf+1024);
  1109.             free_x_buffer=1024;
  1110.         } else if(free_x_buffer<=size_buf) {
  1111.             char *old_x_buffer;
  1112.             char **tmp_ptr;
  1113.  
  1114.             old_x_buffer = x_buffer;
  1115.             x_buffer = (char *)ck_realloc(x_buffer,size_x_buffer+1024);
  1116.             free_x_buffer = 1024;
  1117.             for(tmp_ptr=exclude;tmp_ptr<exclude+size_exclude;tmp_ptr++)
  1118.                 *tmp_ptr= x_buffer + ((*tmp_ptr) - old_x_buffer);
  1119.             for(tmp_ptr=re_exclude;tmp_ptr<re_exclude+size_re_exclude;tmp_ptr++)
  1120.                 *tmp_ptr= x_buffer + ((*tmp_ptr) - old_x_buffer);
  1121.         }
  1122.  
  1123.         if(is_regex(buf)) {
  1124.             if(free_re_exclude==0) {
  1125.                 re_exclude= (char **)(re_exclude ? ck_realloc(re_exclude,(size_re_exclude+32)*sizeof(char *)) : ck_malloc(sizeof(char *)*32));
  1126.                 free_re_exclude+=32;
  1127.             }
  1128.             re_exclude[size_re_exclude]=x_buffer+size_x_buffer;
  1129.             size_re_exclude++;
  1130.             free_re_exclude--;
  1131.         } else {
  1132.             if(free_exclude==0) {
  1133.                 exclude=(char **)(exclude ? ck_realloc(exclude,(size_exclude+32)*sizeof(char *)) : ck_malloc(sizeof(char *)*32));
  1134.                 free_exclude+=32;
  1135.             }
  1136.             exclude[size_exclude]=x_buffer+size_x_buffer;
  1137.             size_exclude++;
  1138.             free_exclude--;
  1139.         }
  1140.         strcpy(x_buffer+size_x_buffer,buf);
  1141.         size_x_buffer+=size_buf+1;
  1142.         free_x_buffer-=size_buf+1;
  1143.     }
  1144.     fclose(fp);
  1145. }
  1146.  
  1147. int
  1148. is_regex(str)
  1149. char *str;
  1150. {
  1151.     return index(str,'*') || index(str,'[') || index(str,'?');
  1152. }
  1153.  
  1154. /* Returns non-zero if the file 'name' should not be added/extracted */
  1155. int
  1156. check_exclude(name)
  1157. char *name;
  1158. {
  1159.     int n;
  1160.  
  1161.     for(n=0;n<size_re_exclude;n++) {
  1162.         if(wildmat(name,re_exclude[n]))
  1163.             return 1;
  1164.     }
  1165.     for(n=0;n<size_exclude;n++) {
  1166.         if(strstr(name,exclude[n]))
  1167.             return 1;
  1168.     }
  1169.     return 0;
  1170. }
  1171.